package com.abel.demo.config.security;

import com.abel.demo.model.SecAuthorityModel;
import com.abel.demo.services.SecAuthorityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Author: Abel.lin
 * Date: Created in 2018/7/17 16:41
 * Company: Abel.Studio
 * Copyright: Copyright (c) 2017
 * Description:
 */
@Service
public class FilterInvocationSecurityMetadataSourceImpl implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private SecAuthorityService authorityService;
    private HashMap<String, Collection<ConfigAttribute>> map = null;

    /**
     * @author: Abel.lin
     * @date: 2018/7/17 16:50
     * @description: 此方法是为了判定用户请求的url 是否在权限表中，如果在权限表中，则返回给 decide 方法，
     *                 用来判定用户是否有此权限。如果不在权限表中则放行。
     * @return:
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object obj) throws IllegalArgumentException {
        if(map == null){
            loadResourceDefine();
        }
        HttpServletRequest request = ((FilterInvocation) obj).getHttpRequest();
        AntPathRequestMatcher matcher;
        String uri;
        for(Iterator<String> iter = map.keySet().iterator(); iter.hasNext();){
            uri = iter.next();
            matcher = new AntPathRequestMatcher(uri);
            if(matcher.matches(request)){
                return map.get(uri);
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

    public void loadResourceDefine(){
        map = new HashMap<>();
        Collection<ConfigAttribute> array;
        ConfigAttribute cfg;
        List<SecAuthorityModel> authorities = authorityService.selectByExample(null);
        for(SecAuthorityModel authority : authorities) {
            array = new ArrayList<>();
            cfg = new SecurityConfig(authority.getCode());
            //此处只添加了用户的名字，其实还可以添加更多权限的信息，例如请求方法到ConfigAttribute的集合中去。此处添加的信息将会作为MyAccessDecisionManager类的decide的第三个参数。
            array.add(cfg);
            //用权限的getUrl() 作为map的key，用ConfigAttribute的集合作为 value，
            map.put(authority.getUri(), array);
        }

    }
}
